package org.xenon.vote.dao.imp;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.xenon.vote.dao.StringDao;
import org.xenon.vote.model.pojo.po.Token;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class TokenDao implements StringDao<Token> {
    private final JdbcTemplate jdbcTemplate;

    public TokenDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void add(Token token) {
        String sql = "insert into `vote`.`token` (`session`, `text`) values (?, ?)";
        jdbcTemplate.update(sql, token.getSession(), token.getText());
    }

    @Override
    @Deprecated
    public void edit(Token token) {
        String sql = "update `vote`.`token` set `text` = ? where `session` = ?";
        jdbcTemplate.update(sql, token.getText(), token.getSession());
    }

    @Override
    public Token get(String session) {
        String sql = "select * from `vote`.`token` where `session` = ?";
        List<Token> list = jdbcTemplate.query(sql, new Object[]{session},TokenRowMapper.getInstance());
        if (list.size() == 0) return null;
        return list.get(0);
    }

    @Deprecated
    @Override
    public List<Token> getAll(String id) {
        return null;
    }

    @Override
    public void del(Token token) {
        String sql = "delete FROM `vote`.`token` WHERE `session` = ?";
        jdbcTemplate.update(sql, token.getSession());
    }

    @Override
    public void del(String session) {
        String sql = "delete FROM `vote`.`token` WHERE `session` = ?";
        jdbcTemplate.update(sql, session);
    }

    /**
     * 自动以RowMapper
     * 提高性能, 使用单例模式
     */
    private static class TokenRowMapper implements RowMapper<Token> {

        private static TokenRowMapper tokenRowMapper;
        @Override
        public Token mapRow(ResultSet rs, int i) throws SQLException {
            return new Token(rs.getString("session"), rs.getString("text"));
        }

        static TokenRowMapper getInstance(){
            if (tokenRowMapper == null){
                synchronized (TokenRowMapper.class){
                    if(tokenRowMapper==null){
                        tokenRowMapper = new TokenRowMapper();
                    }
                }
            }
            return tokenRowMapper;
        }
    }
}
